package com.yuantu.judiciary.serviceimpl;

import com.yuantu.judiciary.model.domain.OrganizationDO;
import com.yuantu.judiciary.service.IApiAliOpenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 阿里外部接口
 *
 * @author syw
 * @since 2023-08-17
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class ApiAliOpenServiceImpl implements IApiAliOpenService {

    private static final String APP_KEY = "203875169";
    private static final String APP_SECRET = "JIEweIVZTFss6LvpPQ5IopAfbe4Swnbb";
    private static final String APP_CODE = "d4e06a4637ef455691910b9c1ee9af95";
    private static final String GET_ORG_INFO_URI = "http://bankpros.market.alicloudapi.com/comdata";

    @Override
    public String getOrgInfo (OrganizationDO organization) {
        // 请求参数
        String params = "com="+ organization.getCreditCode();
        // 发送请求
        return apiStore(GET_ORG_INFO_URI, params, APP_CODE, "POST");
    }

    /**
     * 接口调用
     */
    public static String apiStore(String strUrl, String param, String appcode, String method) {
        // 返回结果定义
        String returnStr;
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(strUrl + "?" + param);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Authorization", "APPCODE " + appcode);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod(method);
            // 不用缓存
            connection.setUseCaches(false);
            connection.connect();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            log.error("阿里外部接口调用异常："+ e.getMessage(), e);
            return "";
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return returnStr;
    }

}
